package com.eschool.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.eschool.dao.RoleDao;
import com.eschool.dao.TeacherDao;
import com.eschool.dao.UserDao;
import com.eschool.model.Teacher;
import com.eschool.model.User;
import com.eschool.service.AlertService;
import com.eschool.service.TeacherService;
import com.eschool.util.ConstraintsUtil;
import com.eschool.util.UserUtil;

public class TeacherServiceImpl implements TeacherService {

	 @Override
	 public boolean addTeacher(Teacher teacher) {
	  
	  teacher.getUser().setAddress(teacher.getPresentAddress());
	  teacher.getUser().setName(teacher.getName());

	  
	  
	  teacher.setBranch(UserUtil.currentUser().getBranch());
	  
	  teacher.getUser().setBranch(teacher.getBranch());
	  teacher.getUser().setPhoneNumber(teacher.getPhoneNumber());
	  teacher.getUser().setAddress(teacher.getPresentAddress());
	  teacher.getUser().setRole(RoleDao.getRoleByProperty("roleId", 2));
	  
	  if((UserDao.getUserByProperty("email", teacher.getUser().getEmail())) != null){
	   return false;
	  }
	  
	  int userId = UserDao.addUser(teacher.getUser());
	  
	  AlertService service = new AlertServiceImpl();
	  
	  List<User> rec = new ArrayList<User>(); rec.add(teacher.getUser());
	  
	  String message = "Your account has been created at JSMSC with following credentials.";
	  message+="\n\tEmail: " + teacher.getUser().getEmail();
	  message+="\n\tPasword: " + teacher.getUser().getPassword();
	  message+="\n\n\tUse " + "http://localhost:8080/eSchool/faces/pages/customer/login.xhtml" + " to login.";
	  
	  service.sendAlert("Account Creation", message, rec, null);
	  
	  if(userId != -1)
	  {   
	   teacher.getUser().setUserId(userId);
	   teacher.setUser(teacher.getUser());
	   if(TeacherDao.addTeacher(teacher) != -1)
	    return true;
	   else
	    return false;
	  }
	  else
	   return false;
	 }

	@Override
	public boolean updateTeacherStatus(List<Teacher> teachers, boolean newStatus) {
		for (Iterator iterator = teachers.iterator(); iterator.hasNext();){
			Teacher teacher = (Teacher) iterator.next();
			teacher.setCurrentStatus(newStatus);
			TeacherDao.updateTeacher(teacher);
		}
		
		
		return true;
	}

	@Override
	public List<Teacher> getAllTeachers() {
		// TODO Auto-generated method stub
		Map<String, Object> constraints = ConstraintsUtil.getConstraintsMap();
		constraints.put("currentStatus", true);
		return TeacherDao.getTeachers(constraints);
	}
	
	@Override
	public List<Teacher> getEnabledTeachers() {
		// TODO Auto-generated method stub
		Map<String, Object> constraints = ConstraintsUtil.getConstraintsMap();
		constraints.put("currentStatus", true);
		return TeacherDao.getTeachers(constraints);
	}
}
